/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */

var levelOrder = function (root) {
    // 初始化结果数组
    const res = []
    if (!root) {
        return res
    }
    // 初始化队列
    const queue = []
    queue.push(root)
    while (queue.length) {
        // 来储存当前节点
        const level = []
        const len = queue.length
        for (let i = 0; i < len; i++) {
            const top = queue.shift()
            level.push(top.val)
            // 如果当前节点存在左子树
            if (top.left) {
                // 推入队列
                queue.push(top.left)
            }
            // 如果当前节点存在右子树
            if (top.right) {
                // 推入队列
                queue.push(top.right)
            }
        }
        res.push(level)
    }
    return res
};